package cn.ailanyin.home.module.user.service.impl;

import cn.ailanyin.home.common.context.UserInfoContext;
import cn.ailanyin.home.common.exception.ServiceException;
import cn.ailanyin.home.common.utils.Sm4Util;
import cn.ailanyin.home.constant.BaseConstant;
import cn.ailanyin.home.module.category.entity.Category;
import cn.ailanyin.home.module.user.dto.UserDTO;
import cn.ailanyin.home.module.user.entity.User;
import cn.ailanyin.home.module.user.mapper.UserMapper;
import cn.ailanyin.home.module.user.service.UserService;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * 用户服务实施
 *
 * @author ailanyin
 * @date 2024/04/13
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;

    @Override
    public User selectByUsername(String username) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        return userMapper.selectOne(wrapper);
    }

    @Override
    public void insert(User user) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, user.getUsername());
        if (userMapper.exists(wrapper)) {
            throw new ServiceException("用户已存在！");
        }
        // 用户状态默认正常
        user.setStatus(BaseConstant.NORMAL);
        userMapper.insert(user);
    }

    @Override
    public User getUser() {
        return userMapper.selectById(UserInfoContext.getUserId());

    }

    @Override
    public void updateUserInfo(UserDTO dto) {
        LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(StrUtil.isNotBlank(dto.getPassword()), User::getPassword, Sm4Util.encrypt(dto.getPassword()))
                .set(StrUtil.isNotBlank(dto.getNickname()), User::getNickname, dto.getNickname())
                .set(StrUtil.isNotBlank(dto.getHomeId()), User::getHomeId, dto.getHomeId())
                .eq(User::getId, UserInfoContext.getUserId());
        userMapper.update(wrapper);
    }
}
